package com.backend.qiniu_manager;

import com.qiniu.common.Zone;
import com.qiniu.util.Auth;
import lombok.Data;

@Data
public class QiNiuConfig {
    ConfigProperties configProperties;

    private String accessKey;
    private String secretKey;
    private String bucket;
    private Zone zone;
    private String domainOfBucket;
    private long expireInSeconds;

    private static QiNiuConfig instance;

    private QiNiuConfig(ConfigProperties Properties){
        this.configProperties = Properties;
        try {
            accessKey = configProperties.getAccessKey();
            secretKey = configProperties.getSecretKey();
            bucket = configProperties.getBucket();
            domainOfBucket = configProperties.getDomainOfBucket();
            expireInSeconds = Long.parseLong(configProperties.getExpireInSeconds());
            String zoneName = configProperties.getZone();
            if(zoneName.equals("zone0")){
                zone = Zone.zone0();
            }else if(zoneName.equals("zone1")){
                zone = Zone.zone1();
            }else if(zoneName.equals("zone2")){
                zone = Zone.zone2();
            }else if(zoneName.equals("zoneNa0")){
                zone = Zone.zoneNa0();
            }else if(zoneName.equals("zoneAs0")){
                zone = Zone.zoneAs0();
            }else{
                throw new Exception("Zone对象配置错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static QiNiuConfig getInstance(ConfigProperties configProperties){
        if(instance == null){
            synchronized (QiNiuConfig.class) {
                if(instance == null){
                    instance = new QiNiuConfig(configProperties);
                }
            }
        }
        return instance;
    }

    /**
     * 生成上传凭证
     * @param key
     * @param override
     * @return
     */
    public String getUploadToken(String key,boolean override){
        //...生成上传凭证，然后准备上传
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken;
        if(override){
            upToken = auth.uploadToken(bucket, key);//覆盖上传凭证
        }else{
            upToken = auth.uploadToken(bucket);
        }
        return upToken;
    }
}
